import 'dart:ui';

import 'package:distribution_mall_flutter/utils/analytics.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_utils.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';

class FirebaseAnalyticsUtils {
  static Map<String, Object?> webParams = EPAnalytics.initWebParams();
  static final FirebaseAnalytics epAnalytics = FirebaseAnalytics.instanceFor(
      app: Firebase.app(Utils.getEnvIsFat() ? 'fat' : '[DEFAULT]'));
  static Future<void> logEvent({
    required String name,
    Map<String, Object?>? parameters,
    AnalyticsCallOptions? callOptions,
  }) async {
    checkFirebase(() {
      epAnalytics.logEvent(
          name: name,
          parameters: {...(parameters ?? {}), ...(webParams)},
          callOptions: callOptions);
    });
  }

  static Future<void> setUserId({
    String? id,
    AnalyticsCallOptions? callOptions,
  }) async {
    checkFirebase(() {
      epAnalytics.setUserId(id: id, callOptions: callOptions);
    });
  }

  static Future<void> setUserProperty({
    required String name,
    required String? value,
    AnalyticsCallOptions? callOptions,
  }) async {
    checkFirebase(() {
      epAnalytics.setUserProperty(
          name: name, value: value, callOptions: callOptions);
    });
  }

  static Future<void> logLogin({
    String? loginMethod,
    Map<String, Object?>? parameters,
    AnalyticsCallOptions? callOptions,
  }) async {
    checkFirebase(() {
      epAnalytics.logLogin(
          loginMethod: loginMethod,
          parameters: parameters,
          callOptions: callOptions);
    });
  }

  static Future<void> logScreenView({
    String? screenName,
  }) async {
    checkFirebase(() {
      epAnalytics.logScreenView(
        screenName: screenName,
      );
    });
  }

  /// Adds parameters that will be set on every event logged from the SDK, including automatic ones.
  static Future<void> setDefaultEventParameters(
    Map<String, Object?>? defaultParameters,
  ) async {
    ///这个不调用checkFirebase.不然没初始化成功,死循环了
    if (Firebase.apps.isNotEmpty) {
      try {
        epAnalytics.setDefaultEventParameters(defaultParameters);
      }catch(e){
        println(e);
      }
    }
  }

  static void checkFirebase(VoidCallback v) {
    if (Firebase.apps.isNotEmpty) {
      v();
    } else {
      ///如果没有就再初始化一遍
      FirebaseUtils.init();
    }
  }
}
